package utils;

import java.lang.reflect.Method;

import sun.print.resources.serviceui;

import advs.ServiceAdvertisement;
import advs.ServicePublisherAdvertisement;

public class ReflectionHelper {
	public static final String SEPARATOR = "_____";

	public static Object GetObjectFromAdv(ServicePublisherAdvertisement adv) {
		Object instance = null;
		try {
			Class classDefinition = Class.forName(adv.getServiceName());
			
			instance = classDefinition.newInstance();

		} catch (Exception exc) {
			System.out.println("ERROR:" + exc.getMessage());
		}
		return instance;
	}

	public static void ExecuteMethodOnObject(Object obj,
			String parametersString, ServicePublisherAdvertisement adv) {
		try {
			Class classDefinition = obj.getClass();

			String[] paramTypes = adv.getParamTypes().split(ReflectionHelper.SEPARATOR);
			Class[] types = new Class[paramTypes.length];
			for (int i = 0; i < types.length; i++) {
				types[i] = Class.forName(paramTypes[i]);
			}

			Method method = classDefinition.getMethod(adv.getServicePath(),
					types);
			String[] reqParams = adv.getReqParam().split(ReflectionHelper.SEPARATOR);
			String[] parameters = parametersString.split(ReflectionHelper.SEPARATOR);
			Object[] callParameters = new Object[types.length];
			for (int i = 0; i < reqParams.length; i++) {
				callParameters[i] = SerializeHelper
						.GetObjectFromString(reqParams[i]);
			}

			for (int i = reqParams.length; i < callParameters.length; i++) {
				callParameters[i] = SerializeHelper
						.GetObjectFromString(parameters[i - reqParams.length]);
			}
			method.invoke(obj, callParameters);

		} catch (Exception exc) {
			System.out.println("ERROR:" + exc.getMessage());
		}
	}
}
